<template>
    <el-card>
        <div class="header-bar">
            <span class="title">多库房/二级库管理</span>
            <el-button type="primary" size="small" @click="onAddWarehouse">新增库房</el-button>
            <el-select v-model="selectedType" placeholder="库房类型" size="small" style="width:120px;margin-left:12px;"
                @change="onTypeChange" clearable>
                <el-option label="全部" value="" />
                <el-option label="一级库" value="一级库" />
                <el-option label="二级库" value="二级库" />
            </el-select>
        </div>
        <div class="warehouse-panel">
            <!-- 左侧库房列表 -->
            <el-menu class="warehouse-list" :default-active="selectedId" @select="onSelectWarehouse" :router="false">
                <el-menu-item v-for="wh in filteredWarehouseList" :key="wh.id" :index="wh.id">
                    {{ wh.name }} <span style="color:#aaa;font-size:13px;">（{{ wh.type }}）</span>
                    <el-button size="small" text type="primary" @click.stop="onEditWarehouse(wh)">编辑</el-button>
                    <el-button size="small" text type="danger" @click.stop="onDeleteWarehouse(wh)">删除</el-button>
                </el-menu-item>
            </el-menu>
            <!-- 右侧库存表 -->
            <div class="warehouse-content">
                <div style="margin-bottom:12px;">
                    <span>库房：</span>
                    <el-tag v-if="currentWarehouse">{{ currentWarehouse.name }}（{{ currentWarehouse.type }}）</el-tag>
                    <el-tag v-else type="info">未选择</el-tag>
                </div>
                <el-table v-if="currentWarehouse" :data="currentWarehouse.materials" border style="width:100%;"
                    height="400px" :row-class-name="rowClassName">
                    <el-table-column prop="id" label="编号" width="110" />
                    <el-table-column prop="name" label="名称" width="130" />
                    <el-table-column prop="stock" label="库存" width="80" />
                    <el-table-column prop="threshold" label="警戒线" width="80" />
                    <el-table-column prop="unit" label="单位" width="60" />
                    <el-table-column prop="expire" label="有效期" width="110" />
                    <el-table-column label="操作" width="180">
                        <template #default="{ row }">
                            <el-button size="small" @click="onEditThreshold(row)">警戒线</el-button>
                            <el-button v-if="currentWarehouse.type === '二级库'" size="small" type="warning"
                                @click="onReturn(row)">退货</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- 新增/编辑库房弹窗 -->
        <el-dialog v-model="whEditVisible" :title="whForm.id ? '编辑库房' : '新增库房'">
            <el-form :model="whForm" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="whForm.name" />
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="whForm.type">
                        <el-option label="一级库" value="一级库" />
                        <el-option label="二级库" value="二级库" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="whEditVisible = false">取消</el-button>
                <el-button type="primary" @click="onSaveWarehouse">保存</el-button>
            </template>
        </el-dialog>

        <!-- 编辑警戒线弹窗 -->
        <el-dialog v-model="thresholdVisible" title="编辑警戒线">
            <el-form :model="thresholdForm" label-width="80px">
                <el-form-item label="警戒线">
                    <el-input-number v-model="thresholdForm.threshold" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="thresholdVisible = false">取消</el-button>
                <el-button type="primary" @click="onSaveThreshold">保存</el-button>
            </template>
        </el-dialog>

        <!-- 二级库退货弹窗 -->
        <el-dialog v-model="returnVisible" title="物资退货到一级库">
            <el-form :model="returnForm" label-width="80px">
                <el-form-item label="数量">
                    <el-input-number v-model="returnForm.amount" :min="1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="returnVisible = false">取消</el-button>
                <el-button type="primary" @click="onReturnConfirm">确定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 多库房模拟数据
const warehouseList = ref([
    {
        id: 'WH1',
        name: '总库房',
        type: '一级库',
        materials: [
            { id: 'M-0001', name: '注射器', stock: 120, threshold: 20, unit: '支', expire: '2025-03-01' },
            { id: 'M-0002', name: '一次性手套', stock: 300, threshold: 30, unit: '盒', expire: '2024-12-15' },
            { id: 'M-0003', name: '纱布', stock: 200, threshold: 40, unit: '包', expire: '2025-01-31' },
            { id: 'M-0004', name: '输液器', stock: 500, threshold: 50, unit: '根', expire: '2025-06-30' },
            { id: 'M-0005', name: '一次性口罩', stock: 1000, threshold: 80, unit: '盒', expire: '2025-02-10' },
            { id: 'M-0006', name: '棉签', stock: 320, threshold: 40, unit: '包', expire: '2025-04-15' },
            { id: 'M-0007', name: '体温计', stock: 60, threshold: 12, unit: '支', expire: '2027-01-01' },
            { id: 'M-0008', name: '输血袋', stock: 90, threshold: 20, unit: '袋', expire: '2026-05-15' },
            { id: 'M-0009', name: '采血针', stock: 180, threshold: 30, unit: '盒', expire: '2025-11-20' },
            { id: 'M-0010', name: '棉球', stock: 160, threshold: 32, unit: '包', expire: '2025-08-01' },
            { id: 'M-0011', name: '医用胶带', stock: 90, threshold: 18, unit: '卷', expire: '2027-12-31' },
            { id: 'M-0012', name: '采血管', stock: 420, threshold: 60, unit: '盒', expire: '2025-09-18' },
            { id: 'M-0013', name: '注射针头', stock: 250, threshold: 50, unit: '盒', expire: '2025-10-11' },
            { id: 'M-0014', name: '尿袋', stock: 110, threshold: 20, unit: '包', expire: '2026-03-22' },
            { id: 'M-0015', name: '棉手套', stock: 220, threshold: 30, unit: '双', expire: '2025-06-12' }
        ]
    },
    {
        id: 'WH2',
        name: '住院部库房',
        type: '二级库',
        materials: [
            { id: 'M-0001', name: '注射器', stock: 30, threshold: 8, unit: '支', expire: '2025-03-01' },
            { id: 'M-0005', name: '一次性口罩', stock: 60, threshold: 12, unit: '盒', expire: '2025-02-10' },
            { id: 'M-0008', name: '输血袋', stock: 10, threshold: 3, unit: '袋', expire: '2026-05-15' },
            { id: 'M-0003', name: '纱布', stock: 18, threshold: 6, unit: '包', expire: '2025-01-31' },
            { id: 'M-0010', name: '棉球', stock: 8, threshold: 2, unit: '包', expire: '2025-08-01' }
        ]
    }
])

const selectedId = ref('WH1')
const selectedType = ref('')
const filteredWarehouseList = computed(() => {
    return warehouseList.value.filter(
        w => !selectedType.value || w.type === selectedType.value
    )
})
const currentWarehouse = computed(() => {
    return warehouseList.value.find(w => w.id === selectedId.value)
})

// 新增/编辑库房
const whEditVisible = ref(false)
const whForm = reactive({ id: '', name: '', type: '一级库' })
function onAddWarehouse() {
    Object.assign(whForm, { id: '', name: '', type: '一级库' })
    whEditVisible.value = true
}
function onEditWarehouse(wh) {
    Object.assign(whForm, { ...wh })
    whEditVisible.value = true
}
function onSaveWarehouse() {
    if (!whForm.name || !whForm.type) {
        ElMessage.warning('名称和类型必填')
        return
    }
    if (whForm.id) {
        // 编辑
        const idx = warehouseList.value.findIndex(w => w.id === whForm.id)
        warehouseList.value[idx] = { ...whForm, materials: warehouseList.value[idx].materials }
        ElMessage.success('编辑成功')
    } else {
        // 新增
        const newId = `WH${Date.now()}`
        warehouseList.value.push({ id: newId, name: whForm.name, type: whForm.type, materials: [] })
        ElMessage.success('新增成功')
    }
    whEditVisible.value = false
}
function onDeleteWarehouse(wh) {
    warehouseList.value = warehouseList.value.filter(w => w.id !== wh.id)
    if (selectedId.value === wh.id) selectedId.value = ''
}
function onSelectWarehouse(id) {
    selectedId.value = id
}
function onTypeChange() {
    // 默认选第一个
    if (filteredWarehouseList.value.length > 0) {
        selectedId.value = filteredWarehouseList.value[0].id
    } else {
        selectedId.value = ''
    }
}

// 编辑警戒线
const thresholdVisible = ref(false)
const thresholdForm = reactive({ id: '', threshold: 0 })
function onEditThreshold(row) {
    Object.assign(thresholdForm, row)
    thresholdVisible.value = true
}
function onSaveThreshold() {
    const wh = currentWarehouse.value
    const idx = wh.materials.findIndex(m => m.id === thresholdForm.id)
    wh.materials[idx].threshold = thresholdForm.threshold
    thresholdVisible.value = false
    ElMessage.success('警戒线已更新')
}

// 退货到一级库
const returnVisible = ref(false)
const returnForm = reactive({ id: '', amount: 1 })
function onReturn(row) {
    Object.assign(returnForm, { id: row.id, amount: 1 })
    returnVisible.value = true
}
function onReturnConfirm() {
    const secWh = currentWarehouse.value
    const mat = secWh.materials.find(m => m.id === returnForm.id)
    if (!mat || mat.stock < returnForm.amount) {
        ElMessage.error('库存不足')
        return
    }
    // 找到一级库并增加库存
    const mainWh = warehouseList.value.find(w => w.type === '一级库')
    if (!mainWh) {
        ElMessage.error('没有一级库')
        return
    }
    let mainMat = mainWh.materials.find(m => m.id === returnForm.id)
    if (!mainMat) {
        // 一级库没有，自动新增
        mainMat = { ...mat, stock: 0 }
        mainWh.materials.push(mainMat)
    }
    mainMat.stock += returnForm.amount
    mat.stock -= returnForm.amount
    ElMessage.success('退货成功')
    returnVisible.value = false
}

// 行警戒线高亮
function rowClassName({ row }) {
    if (row.stock <= row.threshold) return 'row-warning'
    return ''
}
</script>

<style scoped>
.header-bar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.title {
    font-size: 20px;
    font-weight: bold;
    margin-right: 20px;
}

.warehouse-panel {
    display: flex;
    margin-top: 18px;
}

.warehouse-list {
    min-width: 220px;
    max-width: 240px;
    border-right: 0px solid #ebeef5;
    margin-right: 25px;
}

.warehouse-content {
    flex: 1;
}

:deep(.el-table .row-warning) {
    background: #fffbe6;
}
</style>
